package me.zhujin.java.learnjava.myserver;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.Date;

/**
 * Created by zhujin on 10/20/16.
 * blog:www.zhujin.me
 * email: zhujin.nova@gmail.com
 */
public class MyResponse {


    // http response  header
    private StringBuilder headInfo;
    private int response_content_len;
    private StringBuilder responseContext;
    private OutputStream out;

    public MyResponse(Socket client) throws IOException {
        this.headInfo = new StringBuilder();
        this.responseContext = new StringBuilder();
        this.out = client.getOutputStream();
    }


    public MyResponse print(String info) {
        responseContext.append(info);
        response_content_len = response_content_len + info.getBytes().length;
        return this;
    }

    public MyResponse printLn(String info) {
        responseContext.append(info).append(Const.CRLR);
        response_content_len = response_content_len + (info + Const.CRLR).getBytes().length;
        return this;
    }


    public void pushToClilent(int code) throws IOException {
        out.write(createHeadInfo(code));//头信息+分隔符
        //2) 响应正文(Response  body)
        out.write(responseContext.toString().getBytes());
        out.write(Const.CRLR.getBytes());
//        out.close();
    }

    private byte[] createHeadInfo(int code) {

        StringBuffer response = new StringBuffer();
        //1) HTTP 协议版本.状态代码.描述
                response.append("HTTP/1.1").append(Const.BLOCK).append(code).append(Const.BLOCK).append(getState(code)).append(Const.CRLR)
                //2) 响应头(Response  Head)
                .append("Server:zhujin-MyServer1/1.0 ").append(Const.CRLR)
                .append("Date:").append(new Date()).append(Const.CRLR)
                .append("Content-Type:text/html;charset="+ Charset.defaultCharset()).append(Const.CRLR)
                .append("Content-Length:").append(response_content_len).append(Const.CRLR)
                .append(Const.CRLR);
        //2) 响应正文(Response  body)
//                .append(responseContext)
//                .append(Const.CRLR);
        System.out.println(response);
        return response.toString().getBytes();

    }

    private String getState(int code) {
        switch (code) {
            case 200:
                return "OK";
            case 404:
                return "NOT-FOUND";
            case 500:
                return "Server-Error";
            default:
                return "Error-code-" + code;
        }
    }
}
